package procuctconsumer;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Print3{
    Lock lock =new ReentrantLock();
    Condition c1 =lock.newCondition();
    volatile int numer =1;

    public void printC1(int j)  {
        lock.lock();
        try {
            while (numer !=1){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
            for (int i=1;i<=5;i++){
                System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
            }
            numer=2;
            c1.signalAll();
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printC2(int j) {
        lock.lock();
        try {
            while (numer !=2){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
            for (int i=1;i<=10;i++){
                System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
            }
            numer=3;
            c1.signalAll();
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void printC3(int j) {
        lock.lock();
        try {
            while (numer !=3){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+" 开始执行第"+j+"次打印");
            for (int i=1;i<=15;i++){
                System.out.println(Thread.currentThread().getName()+"打印"+i+"次");
            }
            numer=1;
            c1.signalAll();
        }catch (Exception exception){
            exception.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

public class OneCondition {

    public static void main(String[] args) {
        Print3 print =new Print3();

        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC1(i);
            }
        },"c1").start();

        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC2(i);
            }
        },"c2").start();


        new Thread(()->{
            for (int i=1;i<=10;i++){
                print.printC3(i);
            }
        },"c3").start();
    }
}
